package com.kang.util;

import java.sql.*;

/**
 * Created by 12904 on 2018/7/28.
 */
public class BaseDao
{
        //连接数据库地址jdbc:mysql://localhost:3306/数据库名称?useUnicode=true&characterEncoding=UTF-8传入数据库的字符需要的格式
        private static String url="jdbc:mysql://localhost:3306/punifier?useUnicode=true&characterEncoding=UTF-8";
        //数据库用户名
        private static String Uname = "root";
        private static String Upwd = "328201314";
        //需要加载的jdbc驱动
        private static String JDBC = "com.mysql.jdbc.Driver";

        //加载驱动 程序加载时加载驱动
        static{
            try {
                Class.forName(JDBC);
            } catch (ClassNotFoundException e) {
                System.out.println("加载驱动异常"+e.getMessage());
            }
        }

        //获得数据库连接
        public static Connection getConnection(){
            Connection con = null;
            try {
                con = DriverManager.getConnection(url,Uname,Upwd);
            } catch (SQLException e) {
                System.out.println("获取数据库连接失败"+e.getMessage());
            }
            return con;
        }

        //关闭数据连接
        public static void closeConnection(Connection con, PreparedStatement stat , ResultSet rs){
            try {
                if(rs!=null){
                    rs.close();
                }
                if(stat!=null){
                    stat.close();
                }
                if(con!=null){
                    con.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        //增删改通用方法
        public static int executeUpdate(String sql,Object...object) {
            // 返回受影响的行数
            int number = 0;
            // 准备数据库连接对象
            Connection con = null;
            // 准备执行对象
            PreparedStatement stat = null;
            // 	取得数据库连接
            con = BaseDao.getConnection();

            try {
                stat = con.prepareStatement(sql);
                for (int i = 0; i < object.length; i++) {
                    stat.setObject(i+1, object[i]);
                }
                number = stat.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                BaseDao.closeConnection(con, stat, null);
            }
            return number;

        }


}
